package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;


    /*
     * 新增地址
     */
    public void addAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /*
     * 查询当前登录用户的所有地址信息
     */
    public List<AddressBook> showAddressBook() {
       return addressBookMapper.list(AddressBook.builder().userId(BaseContext.getCurrentId()).build());
    }

    /*
     * 查询默认地址
     */
    public AddressBook showDefaultAddressBook() {
        return addressBookMapper.list(AddressBook.builder().userId(BaseContext.getCurrentId()).isDefault(1).build()).get(0);
    }

    /*
     * 根据id查询地址
     */
    public AddressBook getById(Long id) {
        return addressBookMapper.list(AddressBook.builder().userId(BaseContext.getCurrentId()).id(id).build()).get(0);
    }

    /*
     * 根据id修改地址
     */
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /*
     * 设置默认地址
     */
    public void updateDefault(AddressBook addressBook) {
        addressBook.setIsDefault(0);
        //将当前登录用户的所有地址信息都设置为不是默认地址
        addressBookMapper.updateIsDefaultByUserId(addressBook);
        //再将当前传过来的地址设置为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);

    }

    /*
     * 根据id删除地址
     */
    public void deleteById(Long id) {
        addressBookMapper.delete(id);
    }
}
